//
//  ViewController.m
//  Food2ForkTestNhom3
//
//  Created by Lam Quoc on 4/21/15.
//  Copyright (c) 2015 LamQuoc. All rights reserved.
//

#import "ViewController.h"
#import "MH1TableViewCell.h"
#import "MH2ViewController.h"
@interface ViewController ()

@end

@implementation ViewController
NSDictionary* myDictionary;
NSArray* myArray;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Kiem tra font
//    for (NSString* family in  [UIFont familyNames]) {
//        NSLog(@"%@",family);
//        for (NSString *name  in [UIFont fontNamesForFamilyName:family]) {
//            NSLog(@"%@",name);
//        }
//    }
    // Do any additional setup after loading the view, typically from a nib.
    self.myMH1Table.dataSource=self;
    self.myMH1Table.delegate=self;
    
    NSString* urlString =@"http://food2fork.com/api/search?key=869e3bea04b46348efa5db95818f9994";
    
    NSURL* url=[[NSURL alloc]initWithString:urlString];
    NSURLRequest* request = [[NSURLRequest alloc]initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (!connectionError) {
//            NSLog(@"%@",data);
//            NSLog(@"%@",response);
            
            NSError* myError;
            if (!myError) {
                myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&myError];
                myArray = [myDictionary objectForKey:@"recipes"];
//                 NSLog(@"%@",[myDictionary description]);
                //NSLog(@"%@",[myArray description]);
                
            }
            else{
                NSLog(@"%@",myError);
            }
            
           
            [self.myMH1Table reloadData];
            
        }else{
            NSLog(@"%@",connectionError);
        }
    }];
    
  //Navigation
     UIFont *customFont = [UIFont fontWithName:@"AmericanTypewriter" size:20];
    [self.navigationController.navigationBar setBarTintColor:[self colorFromHexString:@"#F5A623"]];
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 35)];
    //lbl.textAlignment = UITextAlignmentCenter;
    lbl.backgroundColor = [UIColor clearColor];
    lbl.text = @"Recipes";
    lbl.font = customFont;
    self.navigationItem.titleView = lbl;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return myArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MH1TableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    if (!cell) {
        [tableView registerClass:[MH1TableViewCell class] forCellReuseIdentifier:@"Cell"];
        cell=[tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    }
    
    NSDictionary* myDic = [myArray objectAtIndex:indexPath.row];
    
    cell.lblNameFood.text=[myDic objectForKey:@"title"];
    cell.lblDescrip.text=[myDic objectForKey:@"publisher"];
    
    // font chu

    UIFont *customFont = [UIFont fontWithName:@"AmericanTypewriter" size:20];
    cell.lblNameFood.font = customFont;
    UIFont *customFont1 = [UIFont fontWithName:@"AmericanTypewriter" size:12];
    cell.lblDescrip.font = customFont1;
    //Mau nen Background chu
    UIColor* colorBackground = [self colorFromHexString:@"#5A3904"];
    [cell.backgroudImage2 setBackgroundColor:colorBackground];
    [cell.backgroudImage2 setAlpha:0.6f];
    
    [cell.myActivity startAnimating];
    NSString* urlString = [myDic objectForKey:@"image_url"];
    
    dispatch_async(dispatch_queue_create("MyImage", nil), ^{
        
        NSURL *url=[[NSURL alloc] initWithString:urlString];
        NSData* myData = [[NSData alloc]initWithContentsOfURL:url];
        
        dispatch_async(dispatch_get_main_queue(), ^{
//            if ([urlString isEqualToString:cell.urlImageString]) {
                cell.backGroundImage.image = [UIImage imageWithData:myData];
                //cell.backGroundImage.opaque=YES;
                [cell.myActivity stopAnimating];
//            UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//            // add effect to an effect view
//            UIVisualEffectView *effectView = [[UIVisualEffectView alloc]initWithEffect:blur];
//            effectView.frame = self.view.frame;
//            
//            // add the effect view to the image view
//            [cell.backGroundImage addSubview:effectView];
            //}
            
            
        });
        
    });
    
    //social_rank
    int rank =(int)[myDic objectForKey:@"social_rank"];
    if (rank>=71) {
        cell.star1.image = [UIImage imageNamed:@"vang.png"];
        cell.star2.image = [UIImage imageNamed:@"vang.png"];
        cell.star3.image = [UIImage imageNamed:@"vang.png"];
    }
    else if (rank<70) {
        cell.star1.image = [UIImage imageNamed:@"xam.png"];
        cell.star2.image = [UIImage imageNamed:@"vang.png"];
        cell.star3.image = [UIImage imageNamed:@"vang.png"];
    }
    else if (rank<40) {
        cell.star1.image = [UIImage imageNamed:@"xam.png"];
        cell.star2.image = [UIImage imageNamed:@"xam.png"];
        cell.star3.image = [UIImage imageNamed:@"vang.png"];
    }
    else if (rank<10) {
        cell.star1.image = [UIImage imageNamed:@"xam.png"];
        cell.star2.image = [UIImage imageNamed:@"xam.png"];
        cell.star3.image = [UIImage imageNamed:@"xam.png"];
    }
    
    
 
    return cell;
}
- (IBAction)ReloadFood:(id)sender {
    [self.myMH1Table reloadData];
}
#pragma mark - Ma mau Hex
- (UIColor *)colorFromHexString:(NSString *)hexString {
    unsigned rgbValue = 0;
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    [scanner setScanLocation:1]; // bypass '#' character
    [scanner scanHexInt:&rgbValue];
    return [UIColor colorWithRed:((rgbValue & 0xFF0000) >> 16)/255.0 green:((rgbValue & 0xFF00) >> 8)/255.0 blue:(rgbValue & 0xFF)/255.0 alpha:1.0];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    NSIndexPath* indexPath = [self.myMH1Table indexPathForSelectedRow];
    
    
    // Lấy dữ liệu của dòng được chọn trong newsList
    NSDictionary* dictionary = [myArray objectAtIndex:indexPath.row];
    
    
    //gán dữ liệu vào viewcontroller chuẩn bị hiển thị.
    // LƯu ý không gán vào các đối tượng IBOutlet/ UIView.
    ((MH2ViewController*)segue.destinationViewController).myIDrecipes = [dictionary objectForKey:@"recipe_id"];
    ((MH2ViewController*)segue.destinationViewController).idArray = [[NSArray alloc]initWithArray:myArray];
    //NSLog(@"%@",[((MH2ViewController*)segue.destinationViewController).idArray description]);
}
@end
